import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.figure import Figure
from src.common.descriptors.user_desc_lib import Log
from datetime import datetime,timedelta
from collections import OrderedDict

def boot_time(logs: list[Log]) -> Figure:
    original_logs = []
    for log in logs:
        duration = log.duration
        start_time = log.start_time
        end_time = start_time + timedelta(seconds=duration)
        original_logs.append((start_time, end_time))
    split_logs = []
    for start, end in original_logs:
        current = start
        while current < end:
            day_start = datetime(current.year, current.month, current.day)
            next_day = day_start + timedelta(days=1)
            segment_end = min(end, next_day)
            split_logs.append((day_start.date(), current.time(), segment_end.time()))
            current = segment_end
    all_dates = sorted({log[0] for log in split_logs})
    week_dict = OrderedDict()
    for date in all_dates:
        week_start = date - timedelta(days=date.weekday())
        week_end = week_start + timedelta(days=6)
        week_key = (week_start, week_end)
        week_dict[week_key] = None
    weeks = list(week_dict.keys())[:4]
    fig, axs = plt.subplots(1, 4, figsize=(12, 6))
    fig.subplots_adjust(bottom=0.18)
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    for week_idx, (week_start, week_end) in enumerate(weeks):
        ax = axs[week_idx]
        axis_start = week_start - timedelta(days=1)
        axis_end = week_end + timedelta(days=1)
        ax.set_xlim(axis_start, axis_end)
        ax.set_xlim(axis_start, axis_end)
        ax.set_ylim(24, 0)
        ax.set_yticks(range(0, 25, 3))
        ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{int(x):02d}:00"))
        week_logs = [
            log for log in split_logs
            if axis_start <= log[0] <= axis_end
        ]
        if week_logs:
            dates = [datetime.combine(date, datetime.min.time()) for date, _, _ in week_logs]
            y_start = [t.hour + t.minute/60 + t.second/3600 for _, t, _ in week_logs]
            y_end = [t.hour + t.minute/60 + t.second/3600 for _, _, t in week_logs]
            
            ax.vlines(
                mdates.date2num(dates), 
                y_start, y_end, 
                colors='#1f77b4', 
                linewidth=4, 
                alpha=0.8
            )
        date_format = "%Y年%m月%d日"
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
        ax.xaxis.set_major_locator(mdates.DayLocator())
        start_str = week_start.strftime(date_format)
        end_str = week_end.strftime(date_format)
        ax.set_title(f"{start_str} - {end_str}", fontsize=10, pad=12)
        ax.set_xlabel('')
        ax.set_ylabel('')
        ax.tick_params(axis='x', rotation=35, labelsize=8)
        ax.tick_params(axis='y', labelsize=8)
        ax.grid(axis='y', color='gray', linestyle=':', alpha=0.3)
        ax.grid(axis='x', color='lightgray', linestyle=':', alpha=0.2)
    plt.tight_layout()
    plt.subplots_adjust(top=0.92, hspace=0.4, wspace=0.25)
    return fig